package com.wmd.validation.validations;

import com.wmd.validation.annotation.DateCompare;
import com.wmd.validation.annotation.DateTime;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @projectName:DocumentLibrary
 * @packageName:com.wmd.validation.validations
 * @Description:TODO
 * @Author:luyincheng
 * @CreateDate: 2023/9/814:50
 */
public class DateCompareValidator implements ConstraintValidator<DateCompare, LocalDateTime> {

    private static DateTimeFormatter dateFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private DateCompare dateCompare;

    @Override
    public void initialize(DateCompare constraintAnnotation) {
        this.dateCompare=constraintAnnotation;
    }

    @Override
    public boolean isValid(LocalDateTime value, ConstraintValidatorContext context) {
        if(value==null){
            return true;
        }
        LocalDateTime beCompareTime= StringUtils.hasLength(dateCompare.compareTime())?LocalDateTime.parse(dateCompare.compareTime(),dateFormatter):LocalDateTime.now();
        int compateResult=value.compareTo(beCompareTime);
        if((dateCompare.greater()&&compateResult>0)||(!dateCompare.greater()&&compateResult<0)){
            return true;
        }
        return false;
    }
}
